package com.loan.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.loan.common.core.domain.PageQuery;
import com.loan.common.core.domain.entity.SysUser;
import com.loan.common.core.page.TableDataInfo;
import com.loan.common.helper.LoginHelper;
import com.loan.common.utils.DateUtils;
import com.loan.common.utils.StringUtils;
import com.loan.system.domain.*;
import com.loan.system.mapper.ApplyMapper;
import com.loan.system.mapper.OverConfigMapper;
import com.loan.system.mapper.OverLastDataMapper;
import com.loan.system.mapper.UserOverMapper;
import com.loan.system.service.CompanyService;
import com.loan.system.service.ISysUserService;
import com.loan.system.service.OverLastDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author shiguang on 2022/10/10 15:18
 */
@Service
@RequiredArgsConstructor
public class OverLastDataServiceImpl implements OverLastDataService {

    private final ApplyMapper applyMapper;

    private final OverLastDataMapper overLastDataMapper;

    private final ISysUserService userService;

    private final CompanyService companyService;

    private final OverConfigMapper overConfigMapper;

    private final UserOverMapper userOverMapper;

    @Override
    public void addLastOverData() {
        String buildDate = DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD);
//        List<Map<String, Object>> list = applyMapper.selectLastOverDataByData(buildDate, null);
//        for (Map<String, Object> map : list) {
//            OverLastDataEntity entity = new OverLastDataEntity();
//            entity.setBuildDate(buildDate);
//            entity.setUserId(Long.valueOf(map.get("userId").toString()));
//            entity.setCompanyId(Long.valueOf(map.get("companyId").toString()));
//            entity.setNum(Integer.valueOf(map.get("num").toString()));
//            entity.setRepayNum(Integer.valueOf(map.get("num1").toString()));
//            entity.setRepayMoney(Integer.valueOf(map.get("repayMoney").toString()));
//            entity.setRemarkNum(Integer.valueOf(map.get("num2").toString()));
//            entity.setCreateTime(new Date());
//            overLastDataMapper.insert(entity);
//        }

        //获取所有公司
        List<CompanyEntity> companyEntityList = companyService.selectList();
        for (CompanyEntity companyEntity : companyEntityList) {
            //获取该公司下s1的催收配置
            List<OverConfigEntity> overConfigList = overConfigMapper.selectList(new QueryWrapper<OverConfigEntity>()
                    .eq("company_id", companyEntity.getId())
                    .eq("del_flag", 0)
                    .orderByAsc("min_day")
                    .last("limit 2,10"));
            if (!CollectionUtils.isEmpty(overConfigList)) {
                for (OverConfigEntity overConfig : overConfigList) {
                    List<UserOverEntity> userOverEntityList = userOverMapper.selectList(new QueryWrapper<UserOverEntity>().eq("over_config_id", overConfig.getId()));
                    if (!CollectionUtils.isEmpty(userOverEntityList)) {
                        for (UserOverEntity userOverEntity : userOverEntityList) {
                            //分配单数
                            Long num = applyMapper.selectCount(new QueryWrapper<ApplyEntity>()
                                    .eq("collection_by", userOverEntity.getUserId())
                                    .eq("del_flag", "0")
                                    .between("over_examine_time", DateUtils.toBeginDateByDay(buildDate), DateUtils.toEndDateByDay(buildDate))
                            );
                            //还款单数
                            Long repayNum = applyMapper.selectCount(new QueryWrapper<ApplyEntity>()
                                    .eq("collection_by", userOverEntity.getUserId())
                                    .eq("del_flag", "0")
                                    .eq("status", "7")
                                    .between("already_repay_time", DateUtils.toBeginDateByDay(buildDate), DateUtils.toEndDateByDay(buildDate))
                            );
                            //还款金额
                            long repayMoney = applyMapper.selectCallMoneyByDate(userOverEntity.getUserId(), buildDate);
                            //当日触达订单数
                            long dayRemarkNum = applyMapper.selectDayRemark(userOverEntity.getUserId(), buildDate);
                            OverLastDataEntity entity = overLastDataMapper.selectOne(new QueryWrapper<OverLastDataEntity>().eq("build_date", buildDate).eq("user_id", userOverEntity.getUserId()));
                            if (ObjectUtil.isNull(entity)) {
                                entity = new OverLastDataEntity();
                            }
                            entity.setBuildDate(buildDate);
                            entity.setUserId(userOverEntity.getUserId());
                            entity.setCompanyId(companyEntity.getId());
                            entity.setNum(Math.toIntExact(num));
                            entity.setRepayNum(Math.toIntExact(repayNum));
                            entity.setRepayMoney(Math.toIntExact(repayMoney));
                            entity.setRemarkNum(Math.toIntExact(dayRemarkNum));
                            entity.setCreateTime(new Date());
                            overLastDataMapper.insertOrUpdate(entity);
                        }
                    }
                }
            }
        }
    }

    @Override
    public TableDataInfo<OverLastDataEntity> selectPageOverLastDataList(String beginTime, String endTime, Long userId, PageQuery pageQuery) {
//        String buildDate = DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD);
//        List<OverLastDataEntity> entityList = new ArrayList<>();
//        List<Map<String, Object>> list = applyMapper.selectLastOverDataByData(buildDate, userId);
//        if (StringUtils.isBlank(beginTime) && StringUtils.isBlank(endTime)) {
//            for (Map<String, Object> map : list) {
//                OverLastDataEntity entity = new OverLastDataEntity();
//                entity.setBuildDate(buildDate);
//                entity.setUserId(Long.valueOf(map.get("userId").toString()));
//                entity.setCompanyId(Long.valueOf(map.get("companyId").toString()));
//                entity.setNum(Integer.valueOf(map.get("num").toString()));
//                entity.setRepayNum(Integer.valueOf(map.get("num1").toString()));
//                entity.setRepayMoney(Integer.valueOf(map.get("repayMoney").toString()));
//                entity.setRemarkNum(Integer.valueOf(map.get("num2").toString()));
//                entity.setCreateTime(new Date());
//                entityList.add(entity);
//            }
//        } else {
//            entityList = overLastDataMapper.selectListTime(beginTime, endTime, userId);
//        }
//        for (OverLastDataEntity entity : entityList) {
//            SysUser user = userService.selectUserById(entity.getUserId());
//            entity.setUserName(user.getUserName());
//            CompanyEntity companyEntity = companyService.selectCompanyById(entity.getCompanyId());
//            entity.setCompanyName(companyEntity.getName());
//        }
//        return entityList;
        Page<OverLastDataEntity> page = overLastDataMapper.selectPageList(pageQuery.build(), this.buildQueryWrapper(beginTime, endTime, userId));
        return TableDataInfo.build(page);
    }

    private Wrapper<OverLastDataEntity> buildQueryWrapper(String beginTime, String endTime, Long userId) {
        QueryWrapper<OverLastDataEntity> wrapper = Wrappers.query();
        Long companyId = LoginHelper.getCompanyId();
        wrapper.eq(ObjectUtil.isNotNull(userId), "vld.user_id", userId)
                .eq(ObjectUtil.isNotNull(companyId), "vld.company_id", companyId)
                .between(StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime), "vld.build_date", beginTime, endTime)
                .orderByDesc("vld.build_date")
                .orderByAsc("vld.company_id")
                .orderByAsc("vld.user_id")
        ;
        return wrapper;
    }

    @Override
    public List<SysUser> listOverUser() {
        List<SysUser> list = new ArrayList<>();
        List<Long> ids = overLastDataMapper.selectOverUserList();
        for (Long id : ids) {
            SysUser user = userService.selectUserById(id);
            list.add(user);
        }
        return list;
    }

    @Override
    public List<OverLastDataEntity> selectList(String beginTime, String endTime, String userId) {
        Long companyId = LoginHelper.getCompanyId();
        List<OverLastDataEntity> list = overLastDataMapper.selectList(new QueryWrapper<OverLastDataEntity>()
                .eq(ObjectUtil.isNotNull(userId), "user_id", userId)
                .eq(ObjectUtil.isNotNull(companyId), "company_id", companyId)
                .between(StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime), "build_date", beginTime, endTime)
                .orderByDesc("build_date")
                .orderByAsc("company_id")
                .orderByAsc("user_id")
        );
        for (OverLastDataEntity entity : list) {
            SysUser user = userService.selectByUserId(entity.getUserId());
            entity.setUserName(user.getUserName());
            CompanyEntity companyEntity = companyService.selectCompanyById(entity.getCompanyId());
            entity.setCompanyName(companyEntity.getName());
        }
        return list;
    }

}
